// 获取入口
var app = document.querySelector("#app") || document.getElementById("app");
//关卡项
var gameLevel = app.querySelector("#gameLeve") || app.getElementById("gameLeve");
//规则项
var gameRule = app.querySelector("#gameRule") || app.getElementById("gameRule");
//游戏区域
var gamePlay = app.querySelector("#gamePlay") || app.getElementById("gamePlay");
// console.log("app:",app,"gameLevel:",gameLevel,"gameRule:",gameRule,"gamePlay:",gamePlay);
//游戏开始的帷幕
var gameStart = app.querySelector("#gameStart") || app.getElementById("gameStart");
//游戏结束的帷幕
var gameEnd = app.querySelector("#gameEnd") || app.getElementById("gameEnd");
//游戏开始的控制按钮
var gameStart_button = gameStart.querySelector("button") || gameStart.getElementsByTagName("button")[0];
//重新开始的按钮
var gameRestart_button = gameEnd.querySelector("button") || gameEnd.getElementsByTagName("button")[0];
/* 
	关系图
		关卡 -->影响--> 顺序数，具体是 关卡数+1 = 顺序数（规则项中的数值）
		顺序数中的数值范围[0,9], 而且不能重复, 还要保留上一关卡的数据
		游戏区域方块的范围在[0,9], 而且必须包含出现的顺序数的数值
 */

/* 
	初始状态
	@level  		关卡，默认从第1关开始
	@ruleArray 		存储规则的数值，初始添加一个随机数
	@playerArray	用户点击的顺序
	@playArea_color	颜色区域
	@color			10中颜色
	@successIndex   用于记录player点击的次数,初始为-1
	@timer			计时器，起始为50s
	@clock			用于setInterval的编号
	@clock_ten		倒计时的十位
	@clock_single	倒计时的个位
 */
//获取设置关卡的span标签
var setLevel;
var setRule;

var level,ruleArray;
var playerArray;
var playArea_color;
var color;
var successIndex;
var timer;
var clock;
var clock_ten;
var clock_single;

//初始化数据
init();
//游戏开始
gameStart.addEventListener("click", function(e){

	if(e.target == gameStart_button){
		gameStart.classList.add('hidden');
		timerStart();
	}
	
});

gameEnd.addEventListener("click", function(e){

	if(e.target == gameRestart_button){
		//初始化数据
		init();
		gameEnd.classList.remove('active');
		timerStart();
	}
	
});


//监听用户的点击事假，用于判断是否符合游戏规则
gamePlay.addEventListener("click", function(e){
	//记录点击中的方块
	click_square = e.target;
	//拿到方块对应的数据
	click_squareData = Number(click_square.innerText);
	console.log("点击对象:",click_square,"值:",click_squareData);
	playerArray.push(click_squareData);
	// console.log("this:", this)
	//判断通过的标志
	this.isSuccess = true;
	
	//console.log("点击元素:",click_square.parentNode.className);
	
	//点击方块才是有效点击，点中空白地方不算
	//需要满足条件:父元素的class值为'row'
	if(click_square.parentNode.className == "row" && click_square.className != 'clock'){
		//点击方块 进行反馈
		click_square.classList.add("active");
		
		successIndex++;
		console.log("successIndex:", successIndex)
	
		if(playerArray[successIndex] != ruleArray[successIndex] || timer < 0){
			this.isSuccess = false;
			alert("Game Over! oOo");
			timerPause();
			gameEnd.classList.add("active");
		}
		if(this.isSuccess && (level == successIndex) && timer >= 0 ){
			console.log("通关");
			setTimeout(nextLevel, 400);
		}
	}
});

function isValid(clicker){
	if(clicker == gamePlay){
		return false;
	}
	return true;
}

//开启倒计时
function timerStart(){
	//每过1s timer-1
	clock = setInterval(function(){
		timer--;
		
		var timerString = String(timer);
		//当倒计时<10的时候，十位应该补0
		if(timer < 10){
			timerString = "0".concat(timerString);
		}
		console.log("timer",timer,"timerString",timerString);
		//刷新
		clock_ten = gamePlay.querySelectorAll(".clock")[0];
		clock_single = gamePlay.querySelectorAll(".clock")[1];
		//渲染
		clock_ten.innerHTML = timerString.substr(0,1);
		clock_single.innerHTML = timerString.substr(1,2);
		
		if(timer < 0){
			timerPause();
			clock_ten.innerHTML = "0";
			clock_single.innerHTML = "0";
			alert("Game Over! oOo");
			gameEnd.classList.add("active");
		}
		
	},1000);
}
//清除计时器
function timerPause(){
	//清除
	clearInterval(clock);
}

function init(){
	level = 1;
	ruleArray =  [];
	playerArray = [];
	playArea_color = new Array(18);
	//粉色 橙色 青绿色 蓝色 淡红色 浅紫色 暗黄色 暗橙色 高亮青绿色 暗深红色
	color = ['#FF3E96', '#FF8C00', '#98FB98', '#6495ED', '#FA8072', '#EE7AE9', '#CDCD00', '#CD661D', '#C1FFC1', '#8B0000'];
	successIndex = -1;
	timer = 50;
	setLevel = gameLevel.querySelector("span")||gameLevel.getElementsByTagName("span")[0];
	setRule = gameRule.querySelector("p")||gameRule.getElementsByTagName("p")[0];
	ruleArray.push(Math.floor(Math.random()*10));
	//初始为第1关，先执行一次
	numFactory(level);
	setLevel.innerHTML = level;
	//传入值时转成字符串，但不写join也会自动转成字符串
	setRule.innerHTML = ruleArray.join(",");
	
	GameRender();
	clock_ten = gamePlay.querySelectorAll(".clock")[0];
	clock_single = gamePlay.querySelectorAll(".clock")[1];
	var timerString = String(timer);
	clock_ten.innerHTML = timerString.substr(0,1);
	clock_single.innerHTML = timerString.substr(1,2);
	timerPause();
}

//进入下一关
function nextLevel(){
	level++;
	playerArray = [];
	successIndex = -1;
	numFactory(level);
	setLevel.innerHTML = level;
	//传入值时转成字符串，但不写join也会自动转成字符串
	setRule.innerHTML = ruleArray.join(",");
	GameRender();
	clock_ten = gamePlay.querySelectorAll(".clock")[0];
	clock_single = gamePlay.querySelectorAll(".clock")[1];
	var timerString = String(timer);
	clock_ten.innerHTML = timerString.substr(0,1);
	clock_single.innerHTML = timerString.substr(1,2);
}

/* 
	*numFactory()		产生顺序数字的工厂，只产生一个随机数与上一个关卡的数组进行对比
		^randomNum		生成[0,9]的随机整数
	*isEqual()			判断两两数值是否相等
	*playFactory		将游戏区域拟作长度为18的数组，然后填充数据
	 	^randomNum		生成[0,9]的随机整数
	* easyGame()		简单的关卡，1~3
		^playArea
		^tempArray
	* GameRender()		数据渲染进页面
 */
function numFactory(time){
	//标记，是否有重复，默认false->没有
	/* var flag = false; */
	//外层i只作为永动机，除非找了合适的randomNum
	/* for(let i = 0; i < 1;){
		var randomNum = Math.floor(Math.random()*10);
		for(var j = 0; j < time; j++){
			if( isEqual(ruleArray[j],randomNum) ){
				flag = true;
				break;
			}
		}
		if(!flag){
			ruleArray.push(randomNum);
			console.log("randomNum",randomNum);
			i++;
		}
	} */
	
	//暂时存放的区域
	var tempArray = [0,1,2,3,4,5,6,7,8,9];
	
	tempArray = filter(tempArray);
	
	var randomNum = Math.floor(Math.random()*tempArray.length);
	
	ruleArray.push(tempArray[randomNum]);
}

function isEqual(a,b){
	if(a === b){
		return true;
	}
	return false;
}

/* 
	- [0,9]10个数都需要被渲染进18个格子 
	* 1~3关为简单:
		规则数组长度为2~4
		规则数组前两个数出现3次，后两个数出现2次，其余随机
	* 4~6关为一般:
		规则数组第一个数出现两次, 后续的数出现一次
	* 7~9关为困难:
		规则数组第一个数出现两次, 后续的数出现一次
*/
function playFactory(){
	//创建一个len为18的数组代表游戏区域
	//值都为undefined
	var playArea = new Array(18);
	//暂时存放的区域
	var tempArray = [0,1,2,3,4,5,6,7,8,9];
	
	tempArray = filter(tempArray);
	
	console.log("tempArray:",tempArray)
	/* >>>>>>>>>>>>简单关卡 1~3 <<<<<<<<<<<<< */ 
	if(ruleArray.length-1 <= 3 ){
		easyGame(playArea,tempArray);
	}
	
	/* >>>>>>>>>>>>一般关卡 4~6 暂时到9关<<<<<<<<<<<<< */
	if(ruleArray.length-1 >= 4 && ruleArray.length-1 <= 9){
		suitLevel(playArea,tempArray);
	}
	
	/* >>>>>>>>>>>>困难关卡 x7~9 暂无<<<<<<<<<<<<< */
	
	return playArea;
}

//过滤已被选择的数值[0,9]
function filter(allNumber){
	//暂时存放的区域
	var tempArray = [];
	
	//过滤
	tempArray = allNumber.filter(function(item,index){
		for(let i = 0; i < ruleArray.length; i++){
			//如果匹配到规则数组中的值，就过滤
			if(item == ruleArray[i]){
				return false
			}
		}
		return true;
	});
	
	return tempArray;
}

/* >>>>>>>>>>>>简单关卡 1~3 <<<<<<<<<<<<< */ 
function easyGame(playArea,tempArray){
	//数值出现的次数
	let time_3 = 3;
	let time_2 = 2;
	//-- 规则数组特殊处理,外层为重复次数，内存为规则数组遍历
	for(let j = 0; j < time_3; j++){
		for(let k = 0; k < ruleArray.length; ){
			//区间是[0,18]
			var randomNum = Math.floor(Math.random()*18);
			//如果方块没有值并且循环次数为2，就赋予值
			if(playArea[randomNum] == undefined && j < time_2){
				playArea[randomNum] = ruleArray[k];
				playArea_color[randomNum] = color[k];
				k++;
			}
			//为循环次数为3的规则数组的前两值给予位置
			if(j == 2  && playArea[randomNum] == undefined){
				if(k >= 2){
					break;
				}
				playArea[randomNum] = ruleArray[k];
				playArea_color[randomNum] = color[k];
				k++;
			}
		}
	}
	console.log("1e-playArea:",playArea);
	
	//--剩余[0,9]的其它数值的处理, 循环次数是小于8(总格子18-前面用了的格子数10)
	var n = 0;//代表tempArray的下标
	for(let m = 0; m < playArea.length; m++){
		if(playArea[m] == undefined){
			playArea[m] = tempArray[n];
			playArea_color[m+ruleArray.length] = color[n];
			n++;
			if(n == tempArray.length){
				n = 0;
			}
		}
	}
	console.log("2e-playArea:",playArea);
}
/* >>>>>>>>>>>>一般关卡 4~6 <<<<<<<<<<<<< */ 
function suitLevel(playArea,tempArray){
	let time_1 = 1;
	let time_2 = 2;
	let time_3 = 3;
	//-- 规则数组特殊处理,外层为重复次数，内存为规则数组遍历
	for(let j = 0; j < time_3; j++){
		for(let k = 0; k < ruleArray.length; ){
			//区间是[0,18]
			var randomNum = Math.floor(Math.random()*18);
			//如果方块没有值并且循环次数为1，就赋予值
			if(playArea[randomNum] == undefined && j == (time_1-1) ){
				playArea[randomNum] = ruleArray[k];
				playArea_color[randomNum] = color[k];
				k++;
			}
			//如果方块没有值并且循环次数为2，就赋予值
			if(playArea[randomNum] == undefined && j == (time_2-1)){
				if( k >= 1 && k <=5 ){
					playArea[randomNum] = ruleArray[k];
					playArea_color[randomNum] = color[k];
				}
				k++;
			}
			//为循环次数为3的规则数组的前两值给予位置
			if(j == (time_3-1)  && playArea[randomNum] == undefined){
				if(k >= 1){
					break;
				}
				playArea[randomNum] = ruleArray[k];
				playArea_color[randomNum] = color[k];
				k++;
			}
		}
	}
	
	//--剩余[0,9]的其它数值的处理, 循环次数是小于8(总格子18-前面用了的格子数10)
	var n = 0;//代表tempArray的下标
	for(let m = 0; m < playArea.length; m++){
		if(playArea[m] == undefined){
			playArea[m] = tempArray[n];
			playArea_color[m+ruleArray.length] = color[n];
			n++;
			if(n == tempArray.length){
				n = 0;
			}
		}
	}
	console.log("2e-playArea:",playArea);
}
/* >>>>>>>>>>>>困难关卡 x7~9 暂无<<<<<<<<<<<<< */
function difficult(playArea,tempArray){
	
}

function GameRender(){
	var playArea = playFactory();
	//获取gamePlay的.row标签
	var gamePlay_row = gamePlay.querySelectorAll(".row");
	var row_inner = "";
	//暂存的一维数组
	var tempArray = [];
	//计次，用于row
	var count = 0;
	console.log("fplayArea:",playArea);
	
	//在10~11添置两个null值，为第三行补足4个子元素
	playArea.splice(9,0,null,null);
	
	console.log("bplayArea:",playArea);
	
	//插入页面
	for(let i = 1; i <= playArea.length; i++){
		if(playArea[i-1] != null){
			row_inner += '<div class="square" style="background-color: '+ playArea_color[i-1] +'">'+ playArea[i-1] +'</div>'
		}else{
			row_inner += '<div class="clock">'+'C'+'</div>'
		}
		if( i % 4 == 0 ){
			gamePlay_row[count].innerHTML = row_inner;
			count++;
			// console.log("count",count);
			//清空
			row_inner = "";
		}
	}
	
}


